<template>
  <xy-page>
    <xy-search>
      <el-form>
        <el-form-item>
          <el-select v-model="opValue" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-date-picker
            v-model="countDate"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            @change="betweenDays"
            clearable
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="right">
        <el-button type="primary" @click="searchAllData">查询</el-button>
        <el-button plain @click="resetForm">重置条件</el-button>
      </div>
    </xy-search>
    <div>
      <ul class="topCountUl">
        <li>
          <div>最高并发（人）</div>
          <div>{{maxNum}}</div>
        </li>
        <li>
          <div>观看次数（次）</div>
          <div>{{viewTimes}}</div>
        </li>
        <li>
          <div>观看时长（分钟）</div>
          <div>{{longTime}}</div>
        </li>
        <li>
          <div>观看ip数（UV）</div>
          <div>{{ipNum}}</div>
        </li>
      </ul>
    </div>
    <el-tabs v-model="activeName" @tab-click="getTabData">
      <!-- 历史并发 -->
      <el-tab-pane label="历史并发" name="历史并发">
        <div id="historyNum"></div>
      </el-tab-pane>
      <!-- 地域分布 -->
      <el-tab-pane label="地域分布" name="地域分布">
        <div class="chartContain">
          <div id="areaCount"></div>
          <div id="countDetail">
            <span>Top 10省市占比</span>
            <el-table :data="topTenData.list">
              <el-table-column label="省份或直辖市" prop="province"></el-table-column>
              <el-table-column label="观看人数" prop="viewer"></el-table-column>
              <el-table-column label="占比" prop="percent"></el-table-column>
            </el-table>
          </div>
        </div>
      </el-tab-pane>
      <!-- 终端分布 -->
      <el-tab-pane label="终端分布" name="终端分布">
        <div class="chartContain">
          <div id="terminCount"></div>
          <div id="countDetail">
            <el-table :data="terminData.seriesData">
              <el-table-column label="观看终端" prop="name"></el-table-column>
              <el-table-column label="观看人数" prop="value"></el-table-column>
              <el-table-column label="占比" prop="percent"></el-table-column>
            </el-table>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </xy-page>
</template>

<script>
export default {
  data() {
    return {
      appId:'',
      sessionKey:'',
      pickerOptions: this.$utils.disabledDate(),
      areaCount:'',
      allProData:{
        list:[]
      },
      topTenData:{
        isloading:false,
        list:[]
      },
      oldOption:'',
      historyDetailData:{
        downloaded:false
      },
      terminDetailData:{
        downloaded:false
      },
      areaDetailData:{
        downloaded:false
      },
      hisTitleData:{
        day:'00-00-00',
        minute:'00:00',
        viewers:0
      },
      province: "",
      areaWatchNum: "2",
      areaDate: "",
      activeName: "历史并发",
      maxNum: 0,
      viewTimes: 0,
      longTime: 0,
      ipNum: 0,
      oldCountDate:'',
      countDate: "",
      opValue: "ALL",
      options: [
        {
          value: "ALL",
          label: "所有应用"
        }
      ],
      hisData: {
        xData: [],
        seriesData: []
      },
      areaData: {
        total:0,
        legendData: [],
        seriesData: []
      },
      terminData: {
        total:0,
        lengendData: [],
        seriesData: []
      },
      historyNum: '', // 历史并发
      terminCount: '', // 终端分布
    }
  },
  mounted() {
    this.oldOption = this.$route.query.appId || 'ALL'
    this.opValue = this.$route.query.appId || 'ALL'
    this.sessionKey = JSON.parse(sessionStorage.getItem('UserInfo')).sessionKey
    this.countDate = [new Date(),new Date()]
    this.searchAllData()
    this.$root.eventHandle.$emit("UPDATE_MENU")
    //获取所有应用
    this.$postStream('/admin/instance/ccb/polyv/app/list.do',{
      data:{},
      success:(res)=>{
        if(res.success){
          this.options = this.options.concat(res.object.list.map(item =>{
            return {
              value: item.devAppId,
              label: item.name
            }
          }))
        }else{
          this.$message.error('下拉框应用列表获取失败')
        }
      },
      error:()=>{
        this.$message.error('下拉框应用列表获取失败')
      }
    })
  },
  methods: {
    betweenDays(){
      if(!this.countDate)return
      if(this.$utils.betweenDays(this.$utils.formatDate(this.countDate[1],'yyyy-MM-dd'),this.$utils.formatDate(this.countDate[0],'yyyy-MM-dd'))>60){
        this.$message.error('时间跨度不能超过60天')
        this.countDate = []
      }
    },
    historyCharts(){
      // 历史并发折线图
      var historyOpt = {
        title: {
          left: "center",
          text: "最高并发观看人数："+this.hisTitleData.viewers+" [时间："+this.hisTitleData.day+" "+this.hisTitleData.minute+"]"
        },
        legend: {
          left: "left",
          data: ["观看人数"]
        },
        tooltip : {
          trigger: 'axis'
        },
        xAxis: {
          type: "category",
          data: this.hisData.xData,
          splitLine: {
            show: true
          },
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          name: "观看人数",
          type: "value",
          splitLine: {
            show: true
          }
        },
        series: [
          {
            name: "观看人数",
            data: this.hisData.seriesData,
            type: "line"
          }
        ],
        dataZoom: [
          {
            type: "slider",
            show: true,
            start: 0, // 从start到end总共分成100份
            end: 100
          },
          {
            type: "inside",
            start: 10,
            end: 90
          }
        ],
        grid: {
          bottom:70
        },
      };
      if(!this.historyNum){
        this.historyNum = this.$echarts.init(document.getElementById("historyNum"))
      }
      this.historyNum.setOption(historyOpt)
    },
    areaCharts(){
      // 地域分布饼图
      var areaOpt = {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
          orient: "vertical",
          right: 50,
          top: 50,
          data: this.areaData.legendData
        },
        series: [
          {
            name: "访问来源",
            type: "pie",
            radius: "60%",
            center: ["50%", "50%"],
            data: this.areaData.seriesData,
            labelLine:{
              length:20,
              length2:10
            }
          }
        ]
      };
      if(!this.areaCount){
        this.areaCount = this.$echarts.init(document.getElementById("areaCount"));
      }
      this.areaCount.setOption(areaOpt);
    },
    terminCharts(){
      // 终端分布饼图
      var terminOpt = {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
          type:'scroll',
          top: 10,
          data: this.terminData.lengendData
        },
        series: [
          {
            name: "访问来源",
            type: "pie",
            radius: "60%",
            center: ["50%", "50%"],
            data: this.terminData.seriesData,
            labelLine:{
              length:20,
              length2:10
            }
          }
        ]
      };
      if(!this.terminCount){
        this.terminCount = this.$echarts.init(document.getElementById("terminCount"));
      }
      this.terminCount.setOption(terminOpt);
    },
    getTabData(){
      //使用oldCountDate来查询，使得历史并发，地域分布，终端分布保持在同一个查询条件下的结果
      if(this.oldOption && this.oldCountDate){
        if(this.activeName == '地域分布'){
          if(this.areaDetailData.downloaded == true)return
          this.getAreaData()
        }else if(this.activeName == '终端分布'){
          if(this.terminDetailData.downloaded == true)return
          this.getTermData()
        }else if(this.activeName == '历史并发'){
          if(this.historyDetailData.downloaded == true)return
          this.getHistoryData()
        }
      }
    },
    getTermData(){
      this.$postStream('/admin/instance/ccb/polyv/app/view/appBrowerStatisSummary.do',{
        data:{
          appId: this.oldOption,
          startDate: this.$utils.formatDate(this.oldCountDate[0],'yyyy-MM-dd'),
          endDate: this.$utils.formatDate(this.oldCountDate[1],'yyyy-MM-dd'),
        },
        success:(res)=>{
          if(res.success){
            this.terminData.lengendData = []
            this.terminData.seriesData = []
            this.terminData.total = 0
            res.object.forEach(item=>{
              this.terminData.lengendData.push(item.browser)
              this.terminData.seriesData.push({name:item.browser,value:item.count})
              this.terminData.total += item.count
            })
            for(let i=0;i<res.object.length;i++){
              this.terminData.seriesData[i].percent = ((res.object[i].count/this.terminData.total)*100).toFixed(2)+'%'
            }
            this.terminDetailData.downloaded = true
            this.terminCharts()
          }else{
            this.$message.error('终端分布获取失败')
          }
        },
        error:()=>{
          this.$message.error('终端分布获取失败')
        }
      })
    },
    getAreaData(){
      this.$postStream('/admin/instance/ccb/polyv/app/view/appGeoStatisSummary.do',{
        data:{
          appId: this.oldOption,
          startDate: this.$utils.formatDate(this.oldCountDate[0],'yyyy-MM-dd'),
          endDate:this.$utils.formatDate(this.oldCountDate[1],'yyyy-MM-dd'),
        },
        success:(res)=>{
          if(res.success){
            this.areaData.legendData = []
            this.areaData.seriesData  = []
            this.areaData.total = 0
            this.allProData.list = []
            this.topTenData.list = []
            this.areaDetailData.downloaded = true
            res.object.forEach(item=>{
              this.areaData.legendData.push(item.province)
              this.areaData.seriesData.push({name:item.province,value:item.viewer})
              this.areaData.total += item.viewer
            })
            this.allProData.list = res.object
            for(let i=0;i<this.allProData.list.length-1;i++){
              for(let j=0;j<this.allProData.list.length-1-i;j++){
                if(this.allProData.list[j].viewer>this.allProData.list[j+1].viewer){
                  let temp=this.allProData.list[j]
                  this.allProData.list[j]=this.allProData.list[j+1]
                  this.allProData.list[j+1]=temp
                }
              }
            }
            if(res.object.length<10){
              const len = res.object.length
              for(let i=0;i<len;i++){
                this.topTenData.list.push(this.allProData.list[i])
                this.topTenData.list[i].percent = ((this.topTenData.list[i].viewer/this.areaData.total)*100).toFixed(2)+'%'
              }
            }else{
              for(let i=0;i<10;i++){
                this.topTenData.list.push(this.allProData.list[i])
                this.topTenData.list[i].percent =((this.topTenData.list[i].viewer/this.areaData.total)*100).toFixed(2)+'%'
              }
            }
            this.areaCharts()
          }else{
            this.$message.error('地域分布获取失败')
          }
        },
        error:()=>{
          this.$message.error('地域分布获取失败')
        }
      })
    },
    searchAllData() {
      this.terminDetailData.downloaded = false
      this.areaDetailData.downloaded = false
      this.historyDetailData.downloaded = false
      this.oldOption = this.opValue
      this.oldCountDate = this.countDate
      if(!this.countDate){
        this.$message.error('日期不能为空')
        return
      }
      //获取应用统计数据
      this.$postStream(
        "/admin/instance/ccb/polyv/app/view/appStatisSummary.do",
        {
          data: {
            appId: this.opValue,
            startDate:this.$utils.formatDate(this.countDate[0],'yyyy-MM-dd'),
            endDate: this.$utils.formatDate(this.countDate[1],'yyyy-MM-dd'),
          },
          success: res => {
            if (res.success) {
              this.maxNum = res.object.concurrenceCount || 0
              this.viewTimes = res.object.videoView || 0
              this.longTime = res.object.playDuration || 0
              this.ipNum = res.object.viewIp || 0
            }else{
              this.$message.error('应用统计数据获取失败')
            }
          },
          error:()=>{
            this.$message.error('应用统计数据获取失败')
          }
        }
      );
      if(this.activeName == '历史并发'){
        this.getHistoryData()
      }else if(this.activeName == '地域分布'){
        this.getAreaData()
      }else if(this.activeName == '终端分布'){
        this.getTermData()
      }
    },
    getHistoryData(){
      //历史并发
      this.$postStream('/admin/instance/ccb/polyv/app/view/appConStatisSummary.do',{
        data:{
          appId: this.opValue,
          startDate: this.$utils.formatDate(this.countDate[0],'yyyy-MM-dd'),
          endDate:this.$utils.formatDate(this.countDate[1],'yyyy-MM-dd'),
        },
        success:(res)=>{
          if(res.success){
            this.historyDetailData.downloaded = true
            this.hisData.xData = []
            this.hisData.seriesData = []
            this.hisTitleData.viewers = 0
            this.hisTitleData.day='00-00-00'
            this.hisTitleData.minute='00:00'
            res.object.forEach(item=>{
              this.hisData.xData.push(item.day+'\n'+item.minute)
              this.hisData.seriesData.push(item.viewers)
              if(item.viewers>=this.hisTitleData.viewers){
                this.hisTitleData.viewers = item.viewers
                this.hisTitleData.day=item.day
                this.hisTitleData.minute=item.minute
              }
            })
            this.historyCharts()
          }else{
            this.$message.error('历史并发获取失败')
          }
        },
        error:()=>{
          this.$message.error('历史并发获取失败')
        }
      })
    },
    resetForm() {
      this.countDate = ''
      this.opValue = ''
    }
  }
};
</script>

<style lang="scss" scoped>
.countUl {
  margin-top: 20px;
  li {
    display: inline-block;
    width: 24%;
    div {
      text-align: center;
    }
    div:nth-of-type(1) {
      font-size: 1.2rem;
      font-weight: bold;
    }
  }
}
.topCountUl {
  margin-top: 20px;
  li {
    display: inline-block;
    width: 24%;
    div {
      text-align: center;
    }
    div:nth-of-type(2) {
      font-size: 2rem;
      font-weight: bold;
    }
  }
}
#historyNum {
  width: 1080px;
  height: 400px;
}
#areaCount,
#terminCount {
  float:left;
  width: 700px;
  height: 600px;
  div {
    width: 700px;
  }
}
.datePick {
  height: 36px;
  width: 25%;
}
#countDetail {
  width:400px;
  float: left;
  margin-top: 50px;
}
.chartContain{
  min-width: 1100px;
}
</style>
<style>
.el-select .el-input .el-select__caret{
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
